package com.scnu.hachimi.show;

import com.scnu.hachimi.controller.KeyboardListener;
import com.scnu.hachimi.element.Bot;
import com.scnu.hachimi.element.Bullet;
import com.scnu.hachimi.element.Player;
import com.scnu.hachimi.manager.ObjectManager;
import com.scnu.hachimi.manager.ResourcesManager;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class TestJFrame extends JFrame {
    private KeyboardListener keyboardListener;
    private ResourcesManager rm;
    private ObjectManager om;

    private Image offScreenImage = null;

    private int w = 800, h = 600;

    public TestJFrame(KeyboardListener keyboardListener, ResourcesManager rm, ObjectManager om) {
        this.keyboardListener = keyboardListener;
        this.rm = rm;
        this.om = om;
    }

    public void paint(Graphics g) {
        if (offScreenImage == null) {
            offScreenImage = this.createImage(w, h);
        }

        Graphics gOff = offScreenImage.getGraphics();

        gOff.clearRect(0, 0, w, h);


        gOff.setColor(Color.black);
        gOff.fillRect(0, 0, w, h);

        // 把全部元素渲染
        for (Player player : om.player) {
            player.paintSelf(gOff, rm);
        }
        for (Bot bot : om.bot) {
            bot.paintSelf(gOff, rm);
        }
        for (Bullet bullet : om.bullet) {
            bullet.paintSelf(gOff, rm);
        }

        g.drawImage(offScreenImage, 0, 0, null);
    }

    public void launch() {
        setTitle("TW");
        setSize(w, h);
        setLocationRelativeTo(null);  // 居中
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);  // 关闭时退出
        setResizable(false);  // 不可改变大小
        setVisible(true);
        this.addKeyListener(this.keyboardListener);

        om.start();

//        Timer timer = new Timer(10, e -> {
//            repaint();
//        });
//        timer.start();

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

        executor.scheduleAtFixedRate(() -> {
            repaint();
        }, 0, 10, java.util.concurrent.TimeUnit.MILLISECONDS);

    }
}
